package com.fusion.minio.controller;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fusion.minio.properties.MinioInfo;
import com.fusion.minio.properties.MinioProperties;
import com.google.api.client.util.IOUtils;
import io.minio.MinioClient;

@RestController
public class MinioController {

	@Autowired
	private MinioClient minioClient;
	@Autowired
	private MinioProperties minioProperties;

	@PostMapping("upload")
	public MinioInfo upload(MultipartFile file) throws Exception {
		String rootPath = minioProperties.getRootPath();
		String url = minioProperties.getUrl();
		boolean bucketExists = minioClient.bucketExists(rootPath);
		if(!bucketExists) {
			minioClient.makeBucket(rootPath);
		}
		InputStream inputStream = file.getInputStream();
		//文件类型
		String contentType = file.getContentType();
		//文件名称
		String fileOldName = file.getOriginalFilename();
		int lastIndexOf = fileOldName.lastIndexOf(".");
		String subSequence = fileOldName.substring(lastIndexOf, fileOldName.length());
		String fileName=UUID.randomUUID().toString()+subSequence;
		//按照日期创建目录
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
		String filePath = simpleDateFormat.format(new Date());
		String filePathName=filePath+"/"+fileName;
		minioClient.putObject(rootPath,filePathName, inputStream, contentType);
		String presignedGetObject = minioClient.presignedGetObject(rootPath, filePathName);
		MinioInfo minioInfo = new MinioInfo();
		minioInfo.setUrl(url);
		minioInfo.setFileName(fileName);
		minioInfo.setFileOldName(fileOldName);
		minioInfo.setRootPath(rootPath);
		minioInfo.setFilePath(filePath);
		minioInfo.setUrlPath(presignedGetObject.replaceAll(url, ""));
		return minioInfo;
	}

	@GetMapping("download")
	public void download(HttpServletResponse response,String filePath, String fileName) throws Exception {
		String rootPath = minioProperties.getRootPath();
		InputStream fileInputStream = minioClient.getObject(rootPath, filePath+"/"+fileName);
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		response.setContentType("application/force-download");
		response.setCharacterEncoding("UTF-8");
		IOUtils.copy(fileInputStream, response.getOutputStream());
	}
	
	@GetMapping("delete")
	public void delete(String filePath, String fileName) throws Exception {
		String rootPath = minioProperties.getRootPath();
		minioClient.removeObject(rootPath, filePath+"/"+fileName);
	}

}
